#!/bin/bash
PROJECT_REAL_PATH=${PROJECT_PATH}/project/${TARGET};

if [[ ${GALAXY} = "deploy" ]];then
    # 使用docker进行编译
    docker build -t galaxy/build:latest deploy/
    docker run --rm --name galaxy-${TARGET} -v ${PROJECT_PATH}:/data -w /data/project/${TARGET} galaxy/build:latest sh -c "go mod download && go mod vendor"
    docker run --rm --name galaxy-${TARGET} -v ${PROJECT_PATH}:/data -w /data/project/${TARGET} galaxy/build:latest go build -mod=vendor main.go
    e=$?
    if [[ ${e} != 0 ]]
    then
        exit ${e}
    fi
else
    # 本地编译
    cd project/${TARGET};
    # Linux
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
    cd ../..;
fi

## 是否执行数据库更新
if [[ -e ${PROJECT_REAL_PATH}/db ]]
then
    if command -v migrate >/dev/null 2>&1; then
        if [[ -f ${PROJECT_REAL_PATH}/config.${ENV}.json ]]
        then
            migrate -path ${PROJECT_REAL_PATH}/db -database "$(cat ${PROJECT_REAL_PATH}/config.${ENV}.json | python -c 'import json,sys,re;print re.sub(r"\@(.*)\/", "@tcp(\\1)/", json.load(sys.stdin)["db"])')" up
        elif [[ -f ${PROJECT_REAL_PATH}/config.${ENV}.yaml ]]
        then
            migrate -path ${PROJECT_REAL_PATH}/db -database "$(cat ${PROJECT_REAL_PATH}/config.${ENV}.yaml | python -c 'import yaml,sys,re;print re.sub(r"\@(.*)\/", "@tcp(\\1)/", yaml.safe_load(sys.stdin)["db"])')" up
        else
            echo "migrate not find config"
            exit 1
        fi
    else
        echo "migrate no exist"
        exit 1
    fi
fi

rm -rf dist
mkdir dist

if [[ -e project/${TARGET}/neutron.unit ]]
then
    mv project/${TARGET}/main dist/${TARGET}
    cat deploy/neutron_install.sh > dist/neutron_install.sh
    . ./project/${TARGET}/neutron.unit
elif [[ -e project/${TARGET}/pm2.json ]]
then
    mv project/${TARGET}/main dist/
    cat project/${TARGET}/pm2.json > dist/pm2.json
    cat deploy/pm2_install.sh > dist/pm2_install.sh
elif [[ -e project/${TARGET}/init.d ]]
then
    mv project/${TARGET}/main dist/
fi

if [[ -e project/${TARGET}/nginx.conf ]]
then
    cat project/${TARGET}/nginx.conf > dist/nginx.conf
    cat deploy/nginx_install.sh > dist/nginx_install.sh
fi
cp -r project/${TARGET}/*.template dist/
if [[ "${Nginx}" = "1" ]]
then
    cat deploy/nginx_install.sh > dist/nginx_install.sh
fi

if [[ -f ${PROJECT_REAL_PATH}/config.${ENV}.json ]]
then
    cat project/${TARGET}/config.${ENV}.json > dist/config.json
elif [[ -f ${PROJECT_REAL_PATH}/config.${ENV}.yaml ]]
then
    cat project/${TARGET}/config.${ENV}.yaml > dist/config.yaml
fi

if [[ -e project/${TARGET}/install.sh ]]
then
    cat project/${TARGET}/install.sh > dist/install.sh
fi

if [[ -f ${PROJECT_REAL_PATH}/pack.sh ]]
then
. ${PROJECT_REAL_PATH}/pack.sh ${PARAMS}
fi

